<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;
use Hash;
class RegisterController extends Controller
{
    //用户登录
	public function register(Request $request)
	{
		if($request -> isMethod('POST'))
		{
			$this -> validate($request,[
				'email' => 'required|email',
				'password' => 'required',
				'captcha' => 'required',
				],[
				'email.required' => '邮箱不能为空',
				'email.email' => '邮箱不合法',
				'password.required' => '密码不能为空',
				'captcha.required' => '验证码不能为空',
				]);
			$data = $request -> except('_token');

			//判断验证码是否正确
    		$c = Session::get('milkcaptcha');
    		if($c != $data['captcha'])
    		{
    			$request -> flash();
    			return back() -> with(['info' => '验证码错误']);
    		}

    		//查询数据
    		$res = DB::table('users') -> where('email',$data['email']) -> first();

            $active = $res -> is_active;
            if($active == 0)
            {
                return back() -> with(['info' => '该用户尚未激活']);
            }

    		if(!$res)
    		{
    			return back() -> with(['info' => '用户名或密码错误']);
    		}

    		$r = Hash::check($data['password'],$res -> password);

    		if(!$r)
    		{
    			return back() -> with(['info' => '用户名或密码错误']);
    		}
    		Session::set('master',$res);
    		return view('home.vip.index');
		}
		return view('home.register');
	}

    //退出登录
	public function logout()
    {
    	
    	Session::forget('master');
    	return redirect('home/vip/index');
    }
}

